package com.styytech.dadabao.ui.my;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.loopj.android.http.RequestParams;
import com.styytech.dadabao.R;
import com.styytech.dadabao.adapter.BankItemAdapter;
import com.styytech.dadabao.api.requestresult.CommonResult;
import com.styytech.dadabao.api.requestresult.ListDataResult;
import com.styytech.dadabao.api.requestresult.MyAccountResult;
import com.styytech.dadabao.api.response.AbstractResponseResult;
import com.styytech.dadabao.api.templates.HttpRequest;
import com.styytech.dadabao.base.BaseActivity;
import com.styytech.dadabao.bean.BankItem;
import com.styytech.dadabao.bean.ListData;
import com.styytech.dadabao.bean.UserAccount;
import com.styytech.dadabao.constant.ConstantsCommon;
import com.styytech.dadabao.constant.ConstantsServerUrl;
import com.styytech.dadabao.exception.ArgumentsException;
import com.styytech.dadabao.exception.RequestException;
import com.styytech.dadabao.utils.CommonUtils;
import com.styytech.dadabao.utils.SpUser;
import com.styytech.dadabao.widge.dialog.CustomLoadingDialog;
import com.styytech.dadabao.widge.dialog.PassWordDialog;

import java.util.LinkedList;

/**
 * Created by mac on 15/12/4.
 */
@ContentView(R.layout.activity_tozfb)
public class ToZfbActivity extends BaseActivity {
    private TimeCount timeCount;
    private CustomLoadingDialog mdlg;
    private CustomLoadingDialog phonedlg;
    private CustomLoadingDialog bankdlg;
    private CustomLoadingDialog checkdlg;
    private CustomLoadingDialog myAccountdlg;

    @ViewInject(R.id.edt_money)
    private EditText edt_money;
    @ViewInject(R.id.tv_phone)
    private TextView tv_phone;
    @ViewInject(R.id.btn_yzm)
    private Button btn_yzm;
    @ViewInject(R.id.edt_yzm)
    private EditText edt_yzm;
    @ViewInject(R.id.bt_apply)
    private Button bt_apply;
    @ViewInject(R.id.tv_name)
    private TextView tv_name;
    @ViewInject(R.id.edt_zfb)
    private EditText edt_zfb;
    private Double before_money;
    private Double money_double;
    private String money_string;
    String phoneNum;
    String phoneString;

    private int position;
    BankItem bankItem;
    PassWordDialog checkDialog;
    private String password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent=getIntent();
        Bundle bundle=intent.getExtras();
        before_money=bundle.getDouble("now_money");
        initViews();
        tv_name.setText(SpUser.getUserInfo(this, ConstantsCommon.USER_REALNAME));
    }
    private void initViews(){
        setTopBar("提现", View.VISIBLE,View.VISIBLE,"返回");
        bankdlg=new CustomLoadingDialog(this,"提示","页面加载中...",false);
        bankdlg.show();

        phoneNum= SpUser.getMobileNumer(this);
        Log.e("asd", "phone-------" + phoneNum);
        phoneString=phoneNum.substring(0,2)+"****"+phoneNum.substring(7);
        tv_phone.setText(phoneString);
        bt_apply.setBackgroundColor(Color.parseColor("#CDC9C9"));
        bt_apply.setClickable(false);
        timeCount = new TimeCount(60000, 1000);
        edt_money.addTextChangedListener(new NumWatcher(edt_money));
        edt_money.setLongClickable(false);
        edt_money.setCustomSelectionActionModeCallback(new ActionMode.Callback() {

            @Override
            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            @Override
            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            @Override
            public void onDestroyActionMode(ActionMode mode) {

            }

            @Override
            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                return false;
            }
        });
    }

    @OnClick({R.id.btn_yzm,R.id.bt_apply})
    private void OnClick(View view){
        switch (view.getId()){
            case R.id.btn_yzm:
                phonedlg=new CustomLoadingDialog(this,"获取验证码","执行中...",false);
                phonedlg.show();
                getCheckCode();
                btn_yzm.setClickable(false);
                break;
            case R.id.bt_apply:
                //判断选择银行卡，判断验证码是否填写
               if(edt_yzm.getText().toString().equals("")){
                    CommonUtils.showToastMsg(ToZfbActivity.this, "请输入您收到的验证码");
                }else if(edt_money.getText().toString().equals("")){
                    CommonUtils.showToastMsg(ToZfbActivity.this, "请输入提现金额");
                } else if(edt_zfb.getText().toString().equals("")){
                   CommonUtils.showToastMsg(ToZfbActivity.this, "请输入您的支付宝帐号");
               } else{
                    money_string=subZeroAndDot(edt_money.getText().toString());
                    money_double = Double.parseDouble(money_string);
                    if (money_double==0){
                        CommonUtils.showToastMsg(ToZfbActivity.this, "输入金额没有意义，请重新输入");
                        return ;
                    }
                    checkCode();
                }
                break;
        }
    }

    private void getCheckCode(){
        String url = ConstantsServerUrl.getCheckCode();
        RequestParams params = new RequestParams();
        params.put("mobileNumber", phoneNum);

        CommonResult logResult = new CommonResult(checkcodeResult);
        try {
            new HttpRequest(this).doPost(logResult,url,params);
        } catch (ArgumentsException e) {
            Log.i("INFO", "1e:" + e);
            e.printStackTrace();
        } catch (RequestException e) {
            Log.i("INFO","2e:"+e);
            e.printStackTrace();
        }
    }

    AbstractResponseResult checkcodeResult = new AbstractResponseResult() {

        @Override
        public void executeSuccess(Object object) {
            // TODO
            Log.e("asd", "object---" + object);
            CommonUtils.showToastMsg(ToZfbActivity.this, "验证码已发送，请注意查收");
            phonedlg.dismiss();
            timeCount.start();
        }

        @Override
        public void executeError(String message, int errorCode) {
            CommonUtils.showToastMsg(ToZfbActivity.this, "" + message);
            phonedlg.dismiss();
        }

        @Override
        public void HttpError(String message, int errorCode) {
            CommonUtils.showToastMsg(ToZfbActivity.this, "" + message);
            phonedlg.dismiss();
        }
    };

    class NumWatcher implements TextWatcher {

        // 监听改变的文本框
        private EditText editText;
        private int editStart;
        private int editEnd;

        /**
         * 构造函数
         */
        public NumWatcher(EditText editText) {
            this.editText = editText;
        }

        @Override
        public void onTextChanged(CharSequence string, int start, int before,
                                  int count) {
            String editable = editText.getText().toString();
            if (string.toString().equals(".")){

                return;
            }else{
                if (string.toString().contains(".")) {
                    if (string.length() - 1 - string.toString().indexOf(".") > 2) {
                        string = string.toString().subSequence(0,
                                string.toString().indexOf(".") + 3);
                        editText.setText(string);
                        editText.setSelection(string.length());
                    }
                }
                if (string.toString().trim().substring(0).equals(".")) {
                    string = "0" + string;
                    editText.setText(string);
                    editText.setSelection(2);
                }

                if (string.toString().startsWith("0")
                        && string.toString().trim().length() > 1) {
                    if (!string.toString().substring(1, 2).equals(".")) {
                        editText.setText(string.subSequence(0, 1));
                        editText.setSelection(1);
                        return;
                    }
                }
            }


        }

        @Override
        public void afterTextChanged(Editable s) {
            editStart = edt_money.getSelectionStart();
            editEnd = edt_money.getSelectionEnd();
            if (!s.toString().equals("")) {
                if (s.toString().equals(".")){
                    s.delete(editStart - 1, editEnd);
                    int tempSelection = editStart;
                    edt_money.setText(s.toString());
                    edt_money.setSelection(tempSelection);
                    return;
                }else{
                    double now_money=Double.parseDouble(s.toString());
                    if (now_money > before_money) {
                        String sss=subZeroAndDot(String.format("%.2f", before_money));
                        Toast.makeText(ToZfbActivity.this, "您只有" + sss + "元可用于提现",
                                Toast.LENGTH_SHORT).show();
                        edt_money.setText(sss);
                        edt_money.setSelection(sss.length());

                    }
                    bt_apply.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_common_selector));
                    bt_apply.setClickable(true);
                }
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

    }

    //去掉小数点后多余的0
    public static String subZeroAndDot(String s){
        if(s.indexOf(".") > 0){
            s = s.replaceAll("0+?$", "");//去掉多余的0
            s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
        }
        return s;
    }
    /* 定义一个倒计时的内部类 */
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);//参数依次为总时长,和计时的时间间隔
        }
        @Override
        public void onFinish() {//计时完毕时触发
            btn_yzm.setText("获取验证码");
            btn_yzm.setClickable(true);
        }
        @Override
        public void onTick(long millisUntilFinished){//计时过程显示
            btn_yzm.setText(millisUntilFinished /1000+"秒后重试");
        }
    }

    //验证支付密码
    private void showCheckDialog(){
        checkDialog = new PassWordDialog(this,money_string,1);
        checkDialog.setEnsureDialogCallback(ensurecallback);
        checkDialog.setCanceleDialogCallback(cancelcallback);
        checkDialog.NotCancel(false);
        checkDialog.show();
    }
    /**
     * 验证支付密码
     */
    PassWordDialog.Dialogcallback ensurecallback = new PassWordDialog.Dialogcallback() {
        @Override
        public void dialogdo() {

            password=checkDialog.getPassword_string();
            if(!password.equals("")){
                getMoney();
                checkDialog.dismiss();
            }else{
                CommonUtils.showToastMsg(ToZfbActivity.this, "请输入支付密码!");
            }


        }
    };
    PassWordDialog.Dialogcallback cancelcallback = new PassWordDialog.Dialogcallback() {
        @Override
        public void dialogdo() {
            checkDialog.dismiss();

        }
    };
    //提现
    private void getMoney(){
        mdlg=new CustomLoadingDialog(this,"提现","申请提交中...",false);
        mdlg.show();
        String url = ConstantsServerUrl.getMoneyUrl();
        RequestParams params = new RequestParams();
        params.put("token",SpUser.getUserToken(this));
        params.put("applyAmount",money_double);
        params.put("userCardId",bankItem.getUserCardId());
        params.put("mobileNumber",phoneNum);
        params.put("checkCode", edt_yzm.getText().toString());
        params.put("payPassword",password);

        CommonResult logResult = new CommonResult(buyResult);
        try {
            new HttpRequest(this).doPost(logResult,url,params);
        } catch (ArgumentsException e) {
            Log.i("INFO","1e:"+e);
            e.printStackTrace();
        } catch (RequestException e) {
            Log.i("INFO","2e:"+e);
            e.printStackTrace();
        }
    }
    /**
     * 支付结果处理
     */
    AbstractResponseResult buyResult = new AbstractResponseResult() {

        @Override
        public void executeSuccess(Object object) {
            // TODO
            mdlg.dismiss();
            CommonUtils.showToastMsg(ToZfbActivity.this, "申请已提交，具体到账时间以银行为准");
            finish();
        }

        @Override
        public void executeError(String message, int errorCode) {
            mdlg.dismiss();
            if (message.equals("账户余额不足,请重新输入提现金额")){
                getMyAccount();
            }
            CommonUtils.showToastMsg(ToZfbActivity.this, "" + message);
        }

        @Override
        public void HttpError(String message, int errorCode) {
            mdlg.dismiss();
            CommonUtils.showToastMsg(ToZfbActivity.this, "" + message);
        }
    };
    public void setListViewHeight(int size,ListView listView) {

        //获取listview的适配器
        ListAdapter listAdapter = listView.getAdapter();
        //item的高度
        int itemHeight = 30;

        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        if (size==1){
            totalHeight += Dp2Px(getApplicationContext(),itemHeight)+listView.getDividerHeight();
            totalHeight=(int)(totalHeight*2);
        }
        if (size==2){
            totalHeight += Dp2Px(getApplicationContext(),itemHeight)+listView.getDividerHeight();
            totalHeight=totalHeight*4;
        }
        if (size==3){
            totalHeight += Dp2Px(getApplicationContext(),itemHeight)+listView.getDividerHeight();
            totalHeight=totalHeight*6;
        }
        if (size>3){
            totalHeight += Dp2Px(getApplicationContext(),itemHeight)+listView.getDividerHeight();
            totalHeight=totalHeight*8;
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight;

        listView.setLayoutParams(params);
    }
    public int Dp2Px(Context context, float dp) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }
    //验证码是否正确
    private void checkCode(){
        checkdlg=new CustomLoadingDialog(this,"验证码","验证中...",false);
        checkdlg.show();
        String url = ConstantsServerUrl.getValidateCheckCode();
        RequestParams params = new RequestParams();
        params.put("mobileNumber",phoneNum);
        params.put("checkCode", edt_yzm.getText().toString());

        CommonResult logResult = new CommonResult(buyResults);
        try {
            new HttpRequest(this).doPost(logResult,url,params);
        } catch (ArgumentsException e) {
            Log.i("INFO","1e:"+e);
            e.printStackTrace();
        } catch (RequestException e) {
            Log.i("INFO","2e:"+e);
            e.printStackTrace();
        }
    }
    /**
     * 验证验证码是否正确
     */
    AbstractResponseResult buyResults = new AbstractResponseResult() {

        @Override
        public void executeSuccess(Object object) {
            // TODO
            checkdlg.dismiss();
            showCheckDialog();
        }

        @Override
        public void executeError(String message, int errorCode) {
            checkdlg.dismiss();
            CommonUtils.showToastMsg(ToZfbActivity.this, "" + message);
        }

        @Override
        public void HttpError(String message, int errorCode) {
            checkdlg.dismiss();
            CommonUtils.showToastMsg(ToZfbActivity.this, "" + message);
        }
    };
    //同步个人信息
    public void getMyAccount() {
        myAccountdlg=new CustomLoadingDialog(this,"同步个人信息","请稍等...",false);
        myAccountdlg.show();
        String url = ConstantsServerUrl.getUserAccountUrl();
        RequestParams params = new RequestParams();

        MyAccountResult logResult = new MyAccountResult(responseResult);
        try {
            new HttpRequest(context).doPost(logResult, url, params);
        } catch (ArgumentsException e) {
            Log.i("INFO", "1e:" + e);
            e.printStackTrace();
        } catch (RequestException e) {
            Log.i("INFO", "2e:" + e);
            e.printStackTrace();
        }
    }
    /**
     * 获取我账户信息
     */
    AbstractResponseResult responseResult = new AbstractResponseResult() {

        @Override
        public void executeSuccess(Object object) {
            UserAccount userAccount = (UserAccount) object;
            CommonUtils.showToastMsg(ToZfbActivity.this, "同步个人信息成功，请重新输入提现金额");
            if (userAccount!=null){
                before_money = userAccount.getAvailableBalance();
            }
            myAccountdlg.dismiss();


        }

        @Override
        public void executeError(String message, int errorCode) {
            myAccountdlg.dismiss();
            CommonUtils.showToastMsg(ToZfbActivity.this, "" + message);

        }

        @Override
        public void HttpError(String message, int errorCode) {
            myAccountdlg.dismiss();
            CommonUtils.showToastMsg(ToZfbActivity.this, "" + message);
        }
    };
}
